<template>
  <!-- 添加一个根容器元素 -->
  <div class="forum-details-container">
    <!-- 右上角返回 -->
    <div class="toolbar">
      <el-button type="danger" icon="Back" @click="goBack">返回</el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container" v-loading="loading" element-loading-text="加载中...">
      <div style="height: 200px;"></div>
    </div>

    <!-- 帖子内容 -->
    <div v-else>
      <!-- 标题区：居中 + 点赞 -->
      <div class="title-row">
        <h2 class="title">{{ postData.forumName || '帖子标题' }}</h2>
        <div class="likes">
          <el-button
              size="small"
              :type="isLiked ? 'primary' : 'default'"
              @click="handleToggleLike"
              :disabled="!currentUser.id"
          >
            <el-icon><Pointer /></el-icon>
            <span class="count">({{ likeCount }})</span>
          </el-button>
        </div>
      </div>

      <!-- 元信息：作者/时间/浏览 -->
      <div class="meta-row">
        <span class="meta-item">发布人：{{ postData.userName || '匿名用户' }}</span>
        <span class="dot">·</span>
        <span class="meta-item">发布日期：{{ formatTime(postData.createTime) }}</span>
        <span class="dot">·</span>
        <span class="meta-item">
          <el-icon class="eye"><View /></el-icon>
          {{ postData.pageViews || 0 }}
        </span>
      </div>

      <!-- 图片区域 -->
      <div class="image-section" v-if="postData.contentImage">
        <el-image
            :src="postData.contentImage"
            fit="cover"
            :preview-src-list="[postData.contentImage]"
            class="forum-image"
        />
      </div>

      <!-- 内容区域 -->
      <div class="content-section">
        <div class="paragraph" v-if="postData.forumContent">
          <p v-for="(seg, i) in splitParagraphs(postData.forumContent)" :key="i">{{ seg }}</p>
        </div>
        <div v-else class="empty">暂无内容</div>
      </div>

      <!-- 评论区 -->
      <div class="comment-section">
        <div class="comment-header">评论 ({{ comments.length }})</div>

        <!-- 评论输入 -->
        <div class="comment-editor">
          <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="说点什么吧..."
              maxlength="500"
              show-word-limit
          />
          <div class="editor-actions">
            <el-button
                type="primary"
                @click="handleSendComment"
                :disabled="!trimmedComment || !currentUser.id"
                :loading="commentSubmitting"
            >
              发送
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list" v-if="comments.length">
          <div
              v-for="item in comments"
              :key="item.id"
              class="comment-item"
              :class="{ me: item.userId === currentUser.id, other: item.userId !== currentUser.id }"
          >
            <!-- 别人的评论 - 左对齐 -->
            <div v-if="item.userId !== currentUser.id" class="other-comment">
              <div class="user-info">
                <div class="name">{{ item.userName }}</div>
                <div class="avatar">
                  <el-avatar :size="36" :src="item.userAvatar">
                    {{ item.userName ? item.userName.charAt(0) : 'U' }}
                  </el-avatar>
                </div>
              </div>
              <div class="message-content">
                <div class="text">{{ item.commentContent }}</div>
                <div class="time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>

            <!-- 自己的评论 - 右对齐 -->
            <div v-else class="me-comment">
              <div class="user-info">
                <div class="name">{{ item.userName }}</div>
                <div class="avatar">
                  <el-avatar :size="36" :src="item.userAvatar">
                    {{ item.userName ? item.userName.charAt(0) : 'U' }}
                  </el-avatar>
                </div>
              </div>
              <div class="message-content">
                <div class="text">{{ item.commentContent }}</div>
                <div class="time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="comment-empty">快来抢沙发~</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { getPostDetail } from '@/api/community/posts'
import { listCommentsByPostsId, addComments } from '@/api/community/comments'
import { getLikeStatus, toggleLike } from '@/api/community/likes'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 数据状态
const loading = ref(true)
const postData = ref({})
const comments = ref([])
const likeCount = ref(0)
const isLiked = ref(false)
const newComment = ref('')
const commentSubmitting = ref(false)

// 计算属性
const trimmedComment = computed(() => newComment.value.trim())

// 当前登录用户信息
const currentUser = reactive({
  id: userStore.id,
  userName: userStore.nickName || userStore.name || '我',
  avatar: userStore.avatar
})

// 返回论坛管理页面
const goBack = () => {
  window.history.back()
  setTimeout(() => window.location.reload(), 50)
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN')
  } catch (e) {
    return timeStr
  }
}

// 将长内容分段显示
const splitParagraphs = (text) => {
  if (!text) return []
  return text.split(/\r?\n\s*\r?\n|[\r\n]/).filter(Boolean)
}

// 加载帖子详情
const loadPostDetail = async () => {
  try {
    loading.value = true
    const postId = route.params.postsId
    const response = await getPostDetail(postId)

    console.log('后端返回数据:', response) // 调试日志

    if (response.code === 200) {
      // 后端数据直接放在response的根级别，不在data字段中
      // 设置帖子数据
      postData.value = response.posts || {}
      // 设置评论数据
      comments.value = response.comments || []
      // 设置点赞数量
      likeCount.value = response.likeCount || 0

      console.log('解析后的数据:', { postData: postData.value, comments: comments.value, likeCount: likeCount.value })

      // 加载点赞状态
      if (currentUser.id) {
        try {
          const likeResponse = await getLikeStatus(postId, currentUser.id)
          // 后端返回的点赞状态在data字段中
          isLiked.value = !!likeResponse.data
        } catch (e) {
          console.warn('获取点赞状态失败:', e)
        }
      }
    } else {
      ElMessage.error(response.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载帖子详情失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 发送评论
const handleSendComment = async () => {
  if (!trimmedComment.value) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (!currentUser.id) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    commentSubmitting.value = true
    const commentData = {
      postsId: postData.value.id,
      userId: currentUser.id,
      userName: currentUser.userName,
      commentContent: trimmedComment.value,
      userAvatar: currentUser.avatar
    }

    const response = await addComments(commentData)
    if (response.code === 200) {
      ElMessage.success('评论成功')
      newComment.value = ''
      // 重新加载评论列表
      await loadComments()
    } else {
      ElMessage.error(response.msg || '评论失败')
    }
  } catch (error) {
    console.error('发送评论失败:', error)
    ElMessage.error('评论失败，请重试')
  } finally {
    commentSubmitting.value = false
  }
}

// 加载评论列表
const loadComments = async () => {
  try {
    const postId = route.params.postsId
    const response = await listCommentsByPostsId(postId)
    if (response.code === 200) {
      // 后端返回的评论列表在data字段中
      comments.value = response.data || []
    }
  } catch (error) {
    console.error('加载评论失败:', error)
  }
}

// 切换点赞状态
const handleToggleLike = async () => {
  if (!currentUser.id) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const postId = postData.value.id
    const response = await toggleLike(postId, currentUser.id)
    if (response.code === 200) {
      // 后端返回的点赞数量在data字段中
      likeCount.value = response.data || 0
      isLiked.value = !isLiked.value
      /*ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞')*/
    } else {
      /*ElMessage.error(response.msg || '操作失败')*/
    }
  } catch (error) {
    /*console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请重试')*/
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadPostDetail()
})
</script>

<style scoped>
.forum-details-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.loading-container {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
}

.likes {
  margin-left: 20px;
}

.count {
  margin-left: 5px;
}

.meta-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.meta-item {
  display: flex;
  align-items: center;
}

.dot {
  margin: 0 8px;
  color: #c0c4cc;
}

.eye {
  margin-right: 4px;
}

/* 图片区域 */
.image-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.forum-image {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  cursor: pointer;
}

/* 内容区域 */
.content-section {
  margin-bottom: 30px;
  padding: 0 20px;
}

.paragraph p {
  line-height: 1.8;
  font-size: 15px;
  color: #303133;
  text-align: justify;
  margin: 0 0 16px;
  text-indent: 2em;
}

.empty {
  color: #c0c4cc;
  text-align: center;
  padding: 20px 0;
}

/* 评论区 */
.comment-section {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
  width: 100%;
}

.comment-header {
  font-weight: 600;
  margin-bottom: 15px;
  font-size: 18px;
  color: #303133;
  text-align: center;
}

.comment-editor {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  background: #fafafa;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.comment-empty {
  color: #c0c4cc;
  text-align: center;
  padding: 20px 0;
}

/* 评论列表 */
.comment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 0 20px;
  max-width: 800px;
  margin: 0 auto;
}

.comment-item {
  width: 100%;
}

/* 别人的评论 - 左对齐 */
.other-comment {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  justify-content: flex-start;
}

.other-comment .user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  min-width: 60px;
  flex-shrink: 0;
}

.other-comment .name {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  text-align: center;
}

.other-comment .avatar {
  flex-shrink: 0;
}

/*.other-comment .message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}*/
.other-comment .message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

/*.other-comment .text {
  background: #f0f0f0;
  padding: 10px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  color: #303133;
  word-break: break-word;
}*/
.other-comment .text {
  background: #f0f0f0;
  padding: 10px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  color: #303133;
  word-break: break-word;
  max-width: 280px; /* 约20个字符的宽度 */
  display: inline-block;
  width: fit-content;
}

.other-comment .time {
  font-size: 11px;
  color: #909399;
  margin-top: 4px;
}

/* 自己的评论 - 右对齐 */
.me-comment {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  justify-content: flex-end;
}

.me-comment .user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  min-width: 60px;
  flex-shrink: 0;
  order: 2;
}

.me-comment .name {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  text-align: center;
}

.me-comment .avatar {
  flex-shrink: 0;
}

/*.me-comment .message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  order: 1;
}*/
.me-comment .message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  order: 1;
  align-items: flex-end;
}

/*.me-comment .text {
  background: #409eff;
  color: white;
  padding: 10px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
}*/

.me-comment .text {
  background: #409eff;
  color: white;
  padding: 10px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
  max-width: 280px; /* 约20个字符的宽度 */
  display: inline-block;
  width: fit-content;
}

.me-comment .time {
  font-size: 11px;
  color: #909399;
  margin-top: 4px;
  text-align: right;
}
</style>




